<template>
  <div class="project">
    <ListTab v-model="activeId" :show-header="!showMobilePage" :tabs="tabList" is-table @tabClick="handleTabClick" />
    <div :class="{'mobile-table mobile-pt mobile-min-height':showMobilePage}" class="table-list min-fill-page">
      <dataDisplay
        v-if="orderStatistics && hasRouteAuth('crm:project:incomeData')"
        ref="dataDisplayRef"
        :data-list="[
          {data: orderStatistics.totalPrice, label: '总含税金额', icon: incomeAmountIcon },
          {data: orderStatistics.totalTaxCost, label: '总成本', icon: costIcon },
          {data: orderStatistics.maori, label: '毛利', icon: rmb },
          {data: orderStatistics.profit, label: '毛利率', unit: '%', icon: maoriIcon }
        ]"
        class="mobile-data"
        style="margin-bottom:16px;"
      />
      <div v-if="!showMobilePage" style="position:relative;margin-bottom:16px;">
        <FilterInput
          ref="FilterToolRef"
          v-model="paramsObj"
          :is-show-filter="isShowFilter"
          :filter-list="filterList"
          show-search-btn
          is-show-config
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"
          @filterTagStatus="filterTagStatus"/>
        <div class="opeator-bar">
          <createBtn v-if="hasRouteAuth('crm:project:add') || isAdmin" style="margin-right:12px;" @click.native="createProject" />
          <el-button v-if="hasRouteAuth('crm:projectChild:read')" plain type="primary" size="small" style="background:#fff;margin:0 12px 0 0;padding: 0 5px;height:32px;color:#406eff;" @click="goOrder">
            <span style="font-size:14px;">查看渠道单明细</span>
          </el-button>
          <btnGroup
            v-if="hasRouteAuth('crm:project:listExport') || isAdmin"
            ref="btnGroupRef"
            :list="[
              {label:'导入', handelClick:uploadDialogShow, auth: hasRouteAuth('crm:project:importAdd') || hasRouteAuth('crm:project:importEdit') },
              {label:'导出',exportApi:'/admin/project/list/export', exportName:'项目列表', beforeExport: exportBeforeExport, type: 'export'},
            ]"
          />
        </div>
      </div>
      <div v-loading="listLoading" style="min-height: 300px;">
        <u-table
          v-if="list.items.length > 0"
          ref="projectTableRef"
          :data="list.items"
          :row-class-name="tableRowClassName"
          :height="computedTableHeight"
          :row-height="rowHeight()"
          :border="true"
          beautify-table
          header-drag-style
          use-virtual
          element-loading-text="加载中..."
          empty-text="暂无数据"
          header-cell-class-name="order-data-header-cell"
          fit
          hightlight-current-row
          @select="selectTable"
          @select-all="selectTable"
          @sort-change="sortMethod">
          <u-table-column
            align="center"
            type="selection"
            width="50"/>
          <u-table-column align="left" label="项目编号" width="180">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.projectNum">
                <router-link
                  :to="{name: 'projectDetail', params: { id: scope.row.id }}"
                  class="project-num ellipsis"
                >{{ scope.row.projectNum }}</router-link>
              </ToolTip>
            </template>
          </u-table-column>
          <u-table-column align="left" label="项目名称" width="220">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.projectName" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="品牌名称" width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.brandName" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="标签" width="150">
            <template slot-scope="scope">
              <TagSelect v-model="scope.row.tag" mode="list" />
              <!-- <ToolTip :content="scope.row.tag" type="arr" label-key="name" /> -->
            </template>
          </u-table-column>
          <u-table-column v-if="clientInfoAuth" align="left" label="客户名称" width="220">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.clientName" />
            </template>
          </u-table-column>
          <u-table-column v-if="clientInfoAuth" align="left" label="实际客户名称" width="220">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.actualClient" />
            </template>
          </u-table-column>
          <u-table-column v-if="clientInfoAuth" align="left" label="客户性质" width="80">
            <template slot-scope="scope">
              <div v-if="scope.row.customerProperty !== null">{{ scope.row.customerProperty | clientType }}</div>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column v-if="hasRouteAuth('crm:project:incomeData')" align="right" label="含税金额(元)" min-width="130" prop="tax_included_amount" sortable="custom">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.taxAmount" :price="scope.row.taxAmount / 100" />
            </template>
          </u-table-column>
          <u-table-column v-if="hasRouteAuth('crm:project:incomeData')" align="right" label="成本金额(元)" min-width="130" prop="cost" sortable="custom">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.costAmount" :price="scope.row.costAmount / 100" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="核销状态" width="100">
            <template slot-scope="scope">
              <StatusText
                :color="scope.row.verificationState === 1 ? '#31CC9C' : '#FD8546'"
                :text="scope.row.verificationState | setVerificationState" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="执行人(商务侧)" width="120">
            <template slot-scope="scope">
              <CheckUserInfo
                v-if="scope.row.businessCooperation"
                :user-list="scope.row.businessCooperation"
                multiple
              />
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="执行人(资源侧)" width="120">
            <template slot-scope="scope">
              <CheckUserInfo
                v-if="scope.row.resourceCooperation"
                :user-list="scope.row.resourceCooperation"
                multiple
              />
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="立项日期" min-width="110" prop="start_project_date" sortable="custom">
            <template slot-scope="scope">
              <div v-if="scope.row.projectApprovalDate">{{ scope.row.projectApprovalDate | standardFormat('YYYY/MM/DD') }}</div>
              <span v-else>--</span>
            </template>
          </u-table-column>
          <u-table-column align="left" label="结案日期" min-width="110" prop="end_project_date" sortable="custom">
            <template slot-scope="scope">
              <div v-if="scope.row.finishDate">{{ scope.row.finishDate | standardFormat('YYYY/MM/DD') }}</div>
              <span v-else>--</span>
            </template>
          </u-table-column>
          <u-table-column align="left" label="状态" width="80">
            <template slot-scope="scope">
              <StatusText
                :color="scope.row.projectStatus === 5 ? '#31CC9C' : '#FD8546'"
                :text="scope.row.projectStatus | projectStatus" />
            </template>
          </u-table-column>
          <u-table-column v-if="hasRouteAuth('crm:project:privacy')" align="left" label="项目备注" width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.projectRemark"/>
            </template>
          </u-table-column>
          <u-table-column v-if="hasRouteAuth('crm:project:privacy')" align="left" label="预计到款" min-width="200" prop="receivePay" sortable="custom">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.receivePay && scope.row.receivePay.length > 0" placement="top">
                <div slot="content" :style="'max-width:180px'">
                  <div v-html="formatReceivePay(scope.row.receivePay, 0)" />
                </div>
                <div>{{ formatReceivePay(scope.row.receivePay) }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="所属部门" width="100">
            <template slot-scope="scope">
              <ToolTip v-if="scope.row.departmentName" :content="(scope.row.attributionMatrixFullName || scope.row.departmentName)">
                <div class="ellipsis">{{ scope.row.departmentName }}</div>
              </ToolTip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建人" width="110">
            <template slot-scope="scope">
              <CheckUserInfo v-if="scope.row.creatorId" :user-id="scope.row.creatorId" :label="scope.row.creator" />
              <span v-else>--</span>
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建时间" min-width="165" prop="create_date" sortable="custom">
            <template slot-scope="scope">
              <div v-if="scope.row.createDate">{{ scope.row.createDate | standardFormat('YYYY/MM/DD HH:mm') }}</div>
              <span v-else>--</span>
            </template>
          </u-table-column>
          <u-table-column align="left" width="110" label="操作" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" @click="toDetail(scope.row)"><span style="font-size:14px;">查看</span></el-button>
              <el-dropdown trigger="click">
                <div class="el-dropdown-link">
                  <el-button type="text"><span style="font-size:14px;">更多<i class="el-icon-arrow-down"/></span></el-button>
                </div>
                <el-dropdown-menu slot="dropdown" style="margin-top:-24px;margin-right:15px;padding: 0;">
                  <el-dropdown-item v-if="editAuth(scope)" style="width:100px;text-align: center" @click.native="toEdit(scope)">
                    <div>编辑</div>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="(scope.row.projectStatus === 1 && (hasRouteAuth('crm:project:firstTrial') || isAdmin)) || (scope.row.projectStatus === 2 && (hasRouteAuth('crm:project:recheck') || isAdmin))" style="width:100px;text-align: center" @click.native="toPulishDialog(scope)">
                    <div>通过</div>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="backAuth(scope.row).auth" style="width:100px;text-align: center" @click.native="toBackDialog(scope)">
                    <div>{{ backAuth(scope.row).text }}</div>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="!scope.row.projectStatus && (hasRouteAuth('crm:project:del') || isAdmin)" style="width:100px;text-align: center" @click.native="toDel(scope.row)">
                    <div>删除</div>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </u-table-column>
        </u-table>
        <empty-placeholder v-else-if="!list.isInit" style="margin-bottom: 24px" />
      </div>
      <el-row v-if="showMobilePage" type="flex" justify="left">
        <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
        <el-pagination
          v-show="list.total > 0"
          :current-page="list.page"
          :page-size="list.perPage"
          :total="list.total"
          :page-sizes="[20, 50, 100, 250, 500]"
          :layout="pageLayout"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </el-row>
      <fixed-pagination v-show="list.total > 0 && !showMobilePage || showMobilePage">
        <template v-if="showMobilePage">
          <FilterInput
            ref="FilterToolRef"
            v-model="paramsObj"
            :is-show-filter="isShowFilter"
            :filter-list="filterList"
            show-search-btn
            show-mobile-icon
            @handelClick="queryClick"
            @queryEmpty="queryEmpty"
            @filterTagStatus="filterTagStatus"/>
          <MoreOpeator
            v-if="hasRouteAuth('crm:project:importAdd') || hasRouteAuth('crm:project:importEdit') || hasRouteAuth('crm:project:listExport') || hasRouteAuth('crm:projectChild:read')"
            ref="moreOpeatorRef"
            :list="[
              {label: '查看渠道单明细', handelClick: goOrder, auth: hasRouteAuth('crm:projectChild:read')},
              {label: '批量导入新增', type:'import', callback: fetchData, importApi:'/admin/project/list/importAdd', auth: hasRouteAuth('crm:project:importAdd') || isAdmin},
              {label: '批量导入编辑', type:'import', callback: fetchData, importApi:'/admin/project/list/importEdit', auth: hasRouteAuth('crm:project:importEdit') || isAdmin},
              {label: '导出', refName: 'exportRef', exportApi:'/admin/project/list/export', exportName:'项目列表', isBeforeExport: true,beforeExport: exportBeforeExportMore, type: 'export', auth: hasRouteAuth('crm:project:listExport') || isAdmin},
            ]"
            show-mobile-icon
          />
          <createBtn v-if="hasRouteAuth('crm:project:add') || isAdmin" mobile-table @click.native="createProject"/>
        </template>
        <template v-else>
          <div style="flex:1;">
            <SelectionNum :select-item="multipleSelectionAll" style="flex:1;" @clearMixinSelection="clearMixinSelection" />
          </div>
          <el-pagination
            v-show="list.total > 0"
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            layout="total, prev, pager, next, sizes, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </template>
      </fixed-pagination>
    </div>
    <projectOpeator ref="projectOpeator" @getInfo="getInfo"/>
    <UploadDialog ref="uploadDialogRef" @uploadList="fetchData" />
  </div>
</template>
<script>
// api
import { getProjectTab, getList, projectDel, getOrderStatistics } from '@/api/project';
import { getTagAll, getDepartmentAll } from '@/api/config';
// components
import ListTab from '@/components/ListTab';
import createBtn from '@/components/Common/baseComponent/createBtn';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import btnGroup from '@/components/Common/baseComponent/btnGroup';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import projectOpeator from '@/components/ProjectComponent/model/projectOpeator';
import dataDisplay from '@/components/Common/baseComponent/dataDisplay';
import TagSelect from '@/components/Common/tagSelect';
import UploadDialog from './model/uploadDialog';
// data
import { clientOption, verificationOptions } from '@/views/project/model/selectData';
// tool
import { clientType, setVerificationState, projectStatus } from '@/filters/status';
import { standardFormat, format } from '@/filters/date';
import { mapState } from 'vuex';
import { hasRouteAuth } from '@/utils/permission';
import { paramsRangeFormat, paramsAryToStr } from '@/utils/paramsFormat';
import { TAG_MODULES } from '@/utils/const';
// 跨页选中逻辑
import tableSelections from '@/mixins/tableSelections';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';
import { showModal } from '@/utils/message';
// img
import incomeAmountIcon from '@/assets/chargeOffDetail/incomeAmount.png';
import maoriIcon from '@/assets/chargeOffDetail/maori.png';
import costIcon from '@/assets/dataDisplay/icon_45.png';
import rmb from '@/assets/dataDisplay/rmb.png';

export default {
  components: { ListTab, btnGroup, MoreOpeator, createBtn, EmptyPlaceholder, projectOpeator, dataDisplay, UploadDialog, TagSelect },
  filters: { clientType, setVerificationState, standardFormat, projectStatus },
  mixins: [tableSelections, TableAdaptive, mobileTable],
  data() {
    return {
      TAG_MODULES,
      tabList: [],
      activeId: -1,
      listLoading: false,
      page: 1,
      perPage: 20,
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInit: true
      },
      rmb,
      costIcon,
      maoriIcon,
      incomeAmountIcon,
      paramsObj: {},
      isShowFilter: false,
      tableRefName: 'projectTableRef', // 表格的ref名称
      idKey: 'id', // 唯一表示字段
      ids: '',
      rangeKeyArr: [
        { attr: 'approvalTime', start: 'projectApprovalStart', end: 'projectApprovalEnd', type: 'time' },
        { attr: 'finishTime', start: 'finishStart', end: 'finishEnd', type: 'time' },
        { attr: 'receivePayTime', start: 'receivePayStart', end: 'receivePayEnd', type: 'time' },
        { attr: 'createTime', start: 'createStart', end: 'createEnd', type: 'time' },
        { attr: 'costTime', start: 'costStartTime', end: 'costEndTime', type: 'time' }
      ],
      arrayKeyArr: ['departmentIds'],
      tagTreeList: [],
      isUmyTable: true,
      orderStatistics: null,
      deptTreeList: []
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    tableOutsideHeight() {
      if (this.showMobilePage) {
        return 262;
      }
      return 246;
    },
    isAdmin() {
      return this.userInfo.userName === '管理员';
    },
    clientInfoAuth() {
      return this.hasRouteAuth('crm:projectInfo:clientInfo') || this.isAdmin;
    },
    activeName() {
      const item = this.tabList.find(i => i.id === this.activeId);
      return item ? item.name : '全部';
    },
    filterList() {
      const dynamicOption = hasRouteAuth('crm:project:privacy')
        ? [
          { keyword: 'receivePayTime', name: '预计到款', labelWidth: '96px', timeType: 'daterange', type: 'rangeDate' },
          { keyword: 'createTime', name: '创建时间', labelWidth: '96px', timeType: 'daterange', type: 'rangeDate' }
        ] : [{ keyword: 'createTime', name: '创建时间', labelWidth: '96px', timeType: 'daterange', type: 'rangeDate' }];
      const arr = [
        // 输入框
        { keyword: 'projectNum', name: '项目编号', labelWidth: '96px', type: 'input' },
        { keyword: 'projectName', name: '项目名称', labelWidth: '96px', type: 'input' },
        { keyword: 'brandName', name: '品牌名称', labelWidth: '96px', type: 'input' },
        { keyword: 'creator', name: '创建人', labelWidth: '96px', type: 'input', doubleClick: true, placeholder: '请输入，双击填充当前用户' },
        { keyword: 'clientName', name: '客户名称', labelWidth: '96px', type: 'input', placeholder: '支持分号搜索多个', disabled: !this.clientInfoAuth },
        { keyword: 'actualClient', name: '实际客户名称', labelWidth: '96px', type: 'input', placeholder: '支持分号搜索多个', disabled: !this.clientInfoAuth },
        { keyword: 'executor', labelWidth: '96px', name: '执行人', type: 'input', doubleClick: true, placeholder: '请输入，双击填充当前用户' },
        { keyword: 'businessCooperation', name: '执行人(商务侧)', labelWidth: '96px', type: 'input', doubleClick: true, placeholder: '请输入，双击填充当前用户' },
        { keyword: 'resourceCooperation', name: '执行人(资源侧)', labelWidth: '96px', type: 'input', doubleClick: true, placeholder: '请输入，双击填充当前用户' },
        { keyword: 'projectDirector', name: '项目总监', labelWidth: '96px', type: 'input', doubleClick: true, placeholder: '请输入，双击填充当前用户' },
        { keyword: 'incomeCreateUser', name: '收入项创建人', labelWidth: '96px', type: 'input', doubleClick: true, placeholder: '请输入，双击填充当前用户' },
        { keyword: 'batchProjectNum', name: '批量搜索项目编号', labelWidth: '96px', type: 'input', inputType: 'textarea',
          lengthLimit: false, placeholder: '可通过粘贴快速填写项目编号，每行代表一个项目编号' },
        // 下拉
        { keyword: 'departmentIds', name: '所属部门', type: 'cascaderSelectWithChild', childrenVal: 'children', options: this.deptTreeList },
        { keyword: 'customerProperty', name: '客户性质', type: 'select', options: clientOption, disabled: !this.clientInfoAuth },
        { keyword: 'verificationState', name: '核销状态', type: 'select', options: verificationOptions },
        { keyword: 'isMyPending', name: '待我处理', type: 'select', options: [
          { value: true, label: '是' }
        ] },
        { keyword: 'relatedInvoice', name: '发票关联状态', type: 'select', options: [{ value: 0, label: '待关联' }, { value: 1, label: '已关联' }] },
        { keyword: 'tag', name: '标签', valueName: 'name', labelName: 'name',
          childrenVal: 'item', type: 'cascaderSelect', checkStrictly: false, options: this.tagTreeList,
          multiple: true, filterable: true, collapseTags: true
        },
        // 日期
        { keyword: 'approvalTime', name: '立项日期', labelWidth: '96px', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'finishTime', name: '结案日期', labelWidth: '96px', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'costTime', labelWidth: '96px', name: '成本创建时间', timeType: 'daterange', type: 'rangeDate' },
        ...dynamicOption
      ];
      return arr;
    },
    computedTableHeight() {
      if (!this.orderStatistics || !hasRouteAuth('crm:project:incomeData')) {
        return Number(this.setTableHeight) + 58 + '';
      }
      return this.setTableHeight;
    }
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'editProject' || from.name === 'projectDetail') {
      to.meta.isChange = true;
    } else {
      to.meta.isChange = false;
    }
    next();
  },
  activated() {
    if (!this.$route.meta.isChange) {
      this.paramsObj = {};
      this.clearMixinSelection();
      if (this.$route.query.batchProjectNum) {
        let { batchProjectNum } = this.$route.query;
        batchProjectNum = batchProjectNum.replace(/,/g, '\n');
        this.$set(this.paramsObj, 'batchProjectNum', batchProjectNum);
      }
      if (this.$route.query.verificationState !== undefined) {
        this.isShowFilter = true;
        this.paramsObj.verificationState = Number(this.$route.query.verificationState);
      } else {
        this.isShowFilter = false;
        this.$set(this.paramsObj, 'verificationState', '');
      }
      if (this.$route.query.executor) {
        this.$set(this.paramsObj, 'executor', this.$route.query.executor);
      }
      this.activeId = this.$route.query.projectStatus !== undefined ? Number(this.$route.query.projectStatus) : -1;
      const hasDefaultPresetFilter = this.$refs.FilterToolRef && this.$refs.FilterToolRef.hasDefaultPresetFilter;
      // 当预设的默认筛选且为第一次进入页面时，不请求数据（会在 filterTool 组件进行筛选）
      if (!this.list.isInit || !hasDefaultPresetFilter) {
        this.fetchData(true);
      }
    } else {
      if (this.list && this.list.items && this.list.items.length === 0) {
        this.fetchData(true);
      } else {
        this.fetchData();
      }
    }
    if (this.list.isInit) {
      this.queryDeptTreeList();
      this.queryTagTreeList();
    }
  },
  methods: {
    hasRouteAuth,
    format,
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
        this.deptTreeList.unshift({ id: -2, name: '--' });
      }).catch(e => {
        console.log(e);
      });
    },
    queryTagTreeList() {
      const params = { type: this.TAG_MODULES.PROJECT };
      getTagAll(params).then(res => {
        this.tagTreeList = (res && res.data) || [];
        this.tagTreeList.forEach(item => {
          if (!item.item) item.disabled = true;
        });
      }).catch(e => {
        console.log(e);
      });
    },
    async getTabList(params) {
      const data = JSON.parse(JSON.stringify(params));
      try {
        delete data.projectStatus;
        const result = await getProjectTab(data);
        if (result.code === 200) {
          this.tabList = result.data;
        }
      } catch (error) {
        this.tabList = [
          { id: -1, name: '全部', num: 0 },
          { id: 0, name: '待提交', num: 0 },
          { id: 1, name: '待初审', num: 0 },
          { id: 2, name: '待复审', num: 0 },
          { id: 3, name: '待确认', num: 0 },
          { id: 4, name: '待封存', num: 0 },
          { id: 5, name: '已封存', num: 0 }
        ];
        console.log(error);
      }
    },
    // 处理预计到款显示
    formatReceivePay(val, isFirstLine = 1) {
      if (!(val && val.length > 0)) return;
      if (isFirstLine) {
        return `第1期：${this.format(val[0].date, 'YYYY/MM/DD')}，${val[0].returnMoney || '--'}元`;
      } else {
        const res = val.map((item, index) => {
          const data = `第${index + 1}期：${this.format(item.date, 'YYYY/MM/DD')}，${item.returnMoney || '--'}元`;
          return '<span style="display:inline-block;max-width:200px;">' + data + '</span>';
        }).join('<br/>');
        return res;
      }
    },
    getParams() {
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      if (this.activeName !== '全部') params.projectStatus = this.activeId; // 设置tab
      // 时间处理
      paramsRangeFormat(this.rangeKeyArr, params);
      paramsAryToStr(this.arrayKeyArr, params);
      if (params.tag && params.tag.length > 0) {
        params.tag = params.tag.join(',');
      }
      params.page = this.page;
      params.perPage = this.perPage;
      params.sortName = this.sortName;
      params.sortType = this.sortType;
      return { ...params, ids: this.ids };
    },
    // 获取统计数据
    async getOrderData() {
      try {
        const params = this.getParams();
        delete params.ids;
        const res = await getOrderStatistics(params);
        if (res.code === 200) {
          this.orderStatistics = res.data;
        }
      } catch (error) {
        console.log(error);
      }
    },
    fetchData(reset = false) {
      if (reset) this.page = 1;
      const params = this.getParams();
      this.listLoading = true;
      delete params.ids;
      this.getTabList(params);
      getList(params).then(({ data }) => {
        data.items = data.items.map(item => {
          if (item.department && item.department.length) item.departmentName = item.department.map(i => i.name).join(',');
          if (item.cooperation && item.cooperation.length) item.cooperationName = item.cooperation.map(i => i.userName).join(',');
          return item;
        });
        this.list = data;
        this.list.isInit = false;
        this.listLoading = false;
        this.page = data.page;
        this.perPage = data.perPage;
        if (this.setSelectRow) this.setSelectRow(data.items);
      }).catch(e => {
        console.error(e);
      });
      this.getOrderData();
    },
    sortMethod(a) {
      if (a.order) {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      } else {
        this.sortName = '';
        this.sortType = '';
      }
      this.fetchData();
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      if (this.clearMixinSelection) this.clearMixinSelection();
      this.fetchData(true);
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData(true);
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData();
    },
    handleTabClick(id) {
      this.activeId = id;
      if (this.clearMixinSelection) this.clearMixinSelection();
      this.fetchData(true);
    },
    editAuth(scope) { // 设置编辑权限判断
      const cooperationName = scope.row.cooperation ? scope.row.cooperation.map(i => i.userName).join(',') : '';
      if (scope.row.projectStatus === 0 || scope.row.projectStatus === 1) {
        if (this.isAdmin) {
          return true;
        } else if (hasRouteAuth('crm:project:editAdmin')) {
          return true;
        } else if (hasRouteAuth('crm:project:edit') && (scope.row.creator === this.userInfo.userName || scope.row.projectDirectorId === this.userInfo.id || cooperationName.indexOf(this.userInfo.userName) >= 0)) {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    },
    goOrder() {
      const projectNums = this.multipleSelectionAll.map(item => item.projectNum).join('\n');
      this.$router.push({ name: 'projectChild', params: { projectNums }});
    },
    createProject() {
      this.$router.push({ name: 'createProject' });
    },
    // 选择表格
    tableSelectionChange(e) {
      this.ids = e.map(item => {
        return item.id;
      }).join(',');
    },
    exportBeforeExport() {
      const params = this.getParams();
      if (this.$refs.btnGroupRef) {
        let msg = '<div>是否确定导出数据？</div>';
        if (!params.ids) {
          msg = msg + `<div style="color: red;font-size: 14px;">单次最多导出5000条</div>`;
        }
        this.$refs.btnGroupRef.btnExport(params, msg);
      }
    },
    exportBeforeExportMore() {
      const params = this.getParams();
      if (this.$refs['moreOpeatorRef']) {
        this.$refs['moreOpeatorRef'].btnExport(params, 'exportRef');
      }
    },
    uploadDialogShow() {
      this.$refs['uploadDialogRef'].dialogShow();
    },
    getInfo() {
      this.fetchData();
    },
    tableRowClassName({ row, rowIndex }) {
      if (this.multipleSelectionAll && this.multipleSelectionAll.length > 0) {
        const ids = this.multipleSelectionAll.map(i => i.id);
        return ids.includes(row.id) ? 'table-selected' : '';
      }
      return '';
    },
    toDetail(row) {
      this.$router.push({
        name: 'projectDetail',
        params: { id: row.id }
      });
    },
    toEdit(scope) {
      this.$router.push({
        name: 'editProject',
        params: { id: scope.row.id }
      });
    },
    toPulishDialog(scope) { // 通过
      const extendParams = { ids: scope.row.id, status: 1 };
      const isMediumSale = scope.row.departmentName ? scope.row.departmentName.indexOf('销售部') >= 0 : false;
      const params = {
        extendParams,
        defaultObjectUser: [],
        projectId: scope.row.id,
        isMediumSale
      };
      if (scope.row.projectStatus === 1) {
        this.$refs.projectOpeator.firstExamine(params);
      } else if (scope.row.projectStatus === 2) {
        if (isMediumSale && scope.row.opeatorUser && scope.row.opeatorUserId) {
          params.defaultObjectUser = [{ id: scope.row.opeatorUserId, userName: scope.row.opeatorUser }];
        }
        this.$refs.projectOpeator.recheckExamine(params);
      }
    },
    toBackDialog(scope) {
      const projectId = scope.row.id;
      const params = {
        extendParams: {
          ids: projectId,
          status: scope.row.projectStatus - 1,
          currentStatus: scope.row.projectStatus
        },
        defaultObjectUser: [],
        projectId: projectId
      };
      if (scope.row.projectStatus === 1) {
        if (scope.row.creator && scope.row.creatorId) {
          params.defaultObjectUser = [{ id: scope.row.creatorId, userName: scope.row.creator }];
        }
        this.$refs.projectOpeator.projectBack(params);
      } else if (scope.row.projectStatus === 2 || scope.row.projectStatus === 3) {
        if (scope.row.opeatorUser && scope.row.opeatorUserId) {
          params.defaultObjectUser = [{ id: scope.row.opeatorUserId, userName: scope.row.opeatorUser }];
        }
        this.$refs.projectOpeator.projectBack(params);
      } else if (scope.row.projectStatus === 4) {
        if (scope.row.opeatorUser && scope.row.opeatorUserId) {
          params.defaultObjectUser = [{ id: scope.row.opeatorUserId, userName: scope.row.opeatorUser }];
        }
        if (scope.row.departmentName) {
          params.extendParams.status = scope.row.departmentName.indexOf('销售部') !== -1 ? 2 : 3;
        } else {
          params.extendParams.status = 3;
        }
        this.$refs.projectOpeator.projectBack(params);
      } else if (scope.row.projectStatus === 5) {
        this.$refs.projectOpeator.cancelSeal({ ids: projectId });
      }
    }, // 撤回
    toDel(row) {
      showModal('是否确定删除项目订单', {
        confirmButtonText: '确定',
        type: 'warning',
        showClose: false,
        center: true,
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        projectDel(row.id).then(res => {
          this.$message.success('删除成功');
          this.clearMixinSelection();
          this.fetchData();
        }).catch(err => {
          console.error(err);
        });
      }).catch(() => {
        return false;
      });
    },
    backAuth(item) { // 撤回权限
      const projectStatusData = Number(item.projectStatus);
      const isMedim = item.departmentName ? item.departmentName.indexOf('销售部') !== -1 : false;
      const isConfirmAuth = !isMedim ? hasRouteAuth('crm:project:confirm') : hasRouteAuth('crm:project:recheck');
      let text = '退回';
      let resultAuth = false;
      switch (projectStatusData) {
        case 1:
          // 待初审 -> 待提交, 拥有初审权限 或者 提交审批权限
          resultAuth = hasRouteAuth('crm:project:firstTrial') || hasRouteAuth('crm:project:submitFirstTrial');
          text = '退回';
          break;
        case 2:
          // 待复审 -> 待初审, 拥有复审权限 或者 初审权限
          resultAuth = hasRouteAuth('crm:project:recheck') || hasRouteAuth('crm:project:firstTrial');
          text = '退回';
          break;
        case 3:
          // 待确认 -> 待复审, 拥有确认权限 或者 复审权限
          resultAuth = hasRouteAuth('crm:project:confirm') || hasRouteAuth('crm:project:recheck');
          text = '退回';
          break;
        case 4:
          // 待封存 -> 待确认 或者（待封存 -> 待复审）
          resultAuth = hasRouteAuth('crm:project:seal') || isConfirmAuth;
          text = '退回';
          break;
        case 5:
          // 已封存 -> 待封存
          resultAuth = hasRouteAuth('crm:project:cancelSeal');
          text = '取消封存';
          break;
      }
      return {
        auth: (resultAuth || this.isAdmin) && projectStatusData > 0,
        text
      };
    }
  }
};
</script>
<style lang="scss" scoped>
.project {
  .el-dropdown-link {
    display: block;
    position: relative;
    padding-left:6px;
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      margin-top: -7px;
      width: 1px;
      background: #ddd;
      height: 14px;
    }
  }
  .table-list {
    margin: 16px 16px 0 16px;
    background-color: #fff;
    padding: 20px 20px 55px 20px;
    .project-num {
      color: #406EFF;
    }
  }
}
.opeator-bar {
  position: absolute;
  right: 0;
  top: 0;
  display: flex;
  align-items: center;
}
</style>
